package com.kun.video.util;

import com.kun.video.AbstractApplication;
import com.kun.video.ui.dialog.ConfirmDialog;
import javafx.application.Platform;
import javafx.scene.control.Label;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/1/26
 **/
public class ComUtil {
    private static final Logger log = LoggerFactory.getLogger(ComUtil.class);
    /**
     * 显示器尺寸信息
     */
    public static final Toolkit TOOLKIT = Toolkit.getDefaultToolkit();
    public static final Dimension DIMENSION = TOOLKIT.getScreenSize();
    public static final DisplayMode DISPLAY_MODE = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();

    /**
     * 主线程执行
     *
     * @param runnable 需要执行的函数
     */
    public static void uiThreadRun(Runnable runnable) {
        if (Platform.isFxApplicationThread()) {
            runnable.run();
        } else {
            Platform.runLater(runnable);
        }
    }

    /**
     * 弹出确认窗口是否重写输出文件（阻塞线程，选择确认框按钮后继续执行原线程代码逻辑）
     *
     * @param outputFile 输出文件对象
     * @return 是否重写输出文件
     */
    public static boolean isOverwriteOutputFileBlockThread(File outputFile) {
        if (!outputFile.exists()) {
            return true;
        }
        AtomicBoolean result = new AtomicBoolean(true);
        // 使用 CountDownLatch 实现线程同步
        CountDownLatch latch = new CountDownLatch(1);
        ComUtil.uiThreadRun(() -> {
            try {
                log.info("是否覆盖文件{}", outputFile.getAbsolutePath());
                // 弹出确认窗口
                ConfirmDialog confirmDialog = new ConfirmDialog("覆盖文件确认", AbstractApplication.getAppStage());
                confirmDialog.setCenter(new Label("是否覆盖文件" + outputFile.getAbsolutePath()));
                if (!confirmDialog.showAndWaitResult()) {
                    result.set(false);
                }
            } finally {
                // 释放锁
                latch.countDown();
            }
        });
        try {
            // 阻塞当前线程，等待用户交互完成
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("线程被中断：{}", e.getMessage());
        }
        return result.get();
    }

}
